﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ_Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQ_COM.Exchange
{
    /// <summary>
    /// 完全匹配
    /// </summary>
    public class Direct
    {
        public static void Consumption()
        {
            using (var connection = RabbitMQHelper.GetConnection())
            {
                using (var channel = connection.CreateModel())//创建信道，通信管道
                {
                    channel.ExchangeDeclare("direct_exchange", "direct");
                    //创建队列
                    //创建队列
                    var queue = "directtest3";
                    channel.QueueDeclare(queue, false, false, false, null);
                    //var queue2 = "test2";
                    //channel.QueueDeclare(queue2, false, false, false, null);
                    //var queue3 = "test3";
                    //channel.QueueDeclare(queue3, false, false, false, null);
                    //绑定交换机
                    string[] routingKeyList = new string[] {  "yel1l" };
                    foreach(var row in routingKeyList)
                    {
                        channel.QueueBind(queue, "direct_exchange", row);
                    }
                    
                    //channel.QueueBind(queue2, "direct_exchange", "");
                    //channel.QueueBind(queue3, "direct_exchange", "");
                    while (true)
                    {
                        //没绑定交换机，但由于rabbitmq有默认交换机
                        var consumer = new EventingBasicConsumer(channel);
                        consumer.Received += (model, ea) =>
                        {
                            var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                            Console.WriteLine(message);
                            //消息完成后需要手动签收消息，如果不写下面代码，容易导致重复消费
                            channel.BasicAck(ea.DeliveryTag,true);//可以降低每次签收的性能损耗
                        };
                        //消息签收模式
                        //手动签收：false 避免消息丢失
                        //自动签收：true 容易丢消息
                        channel.BasicConsume(queue, autoAck: false, consumer);
                        Thread.Sleep(1000);
                    }


                }
            }
        }
    }
}
